#include "widget.h"
#include "qjsonobject.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    


    connect(ts,&QTcpServer::newConnection,this,[=](){
        QTcpSocket* newtso=ts->nextPendingConnection();
        ui->meslist->addItem("new connection is coming");
        connect(newtso,&QTcpSocket::readyRead,this,[=](){
            QByteArray ba=newtso->readAll();
            qDebug()<<"QBytearray-size"<<ba.size();
            QJsonDocument jd=QJsonDocument::fromJson(ba);
            QJsonObject jo=jd.object();
            QString dt=jo.value("datatype").toString();
            qDebug()<<"datatype:"<<dt<<"is coming";
            if(dt=="enrollaccount")
            {
                bool success=true;
                QString account=jo.value("account").toString();
                QString mes="account:"+account+" send datatype:enrollaccount";
                ui->meslist->addItem(mes);
                if(Accounts.find(account)!=Accounts.end())
                    success=false;
                if(success)
                {
                    //导入内存
                    Accounts.insert(account);
                    qDebug()<<"success";
                    QString name=jo.value("name").toString();
                    QString secret=jo.value("secret").toString();
                    QString image=":/res/login_default.png";  //注册时使用默认图像
                    peopleinfo* pi=new peopleinfo;
                    pi->init(account,name,secret,image,"","",newtso);
                    PeopleInfos[account]=pi;
                    //插入用户信息到数据库
                    QJsonObject sendjo;
                    sendjo.insert("datatype","insertpeopleinfo");
                    sendjo.insert("account",account);
                    sendjo.insert("secret",secret);
                    sendjo.insert("image",image);
                    sendjo.insert("name",name);
                    QJsonDocument sendjd(sendjo);
                    QByteArray byr=sendjd.toJson();
                    byr.append('@');
                    qDebug()<<"enrollaccount-size:"<<ts_sql->write(byr);
                    ts_sql->waitForBytesWritten();
                    //创建用户对应的朋友表和消息表
                    QJsonObject sendjo1;
                    sendjo1.insert("datatype","createtable");
                    sendjo1.insert("account",account);
                    QJsonDocument sendjd1(sendjo1);
                    QByteArray byr1=sendjd1.toJson();
                    byr1.append('@');
                    ts_sql->write(byr1);
                    ts_sql->waitForBytesWritten();
                }
                
                QJsonObject sendjo;
                sendjo.insert("datatype","enrollinfo");
                sendjo.insert("enrollsuccess",success);
                QJsonDocument sendjd(sendjo);
                newtso->write(sendjd.toJson());
                mes="success datatype:enrollaccount response to account:"+account;
                ui->meslist->addItem(mes);
            }
            else if(dt=="accountexist")
            {
                bool exist=false;
                QString account=jo.value("account").toString();
                QJsonObject sendjo;
                if(Accounts.find(account)!=Accounts.end())
                {
                    PeopleInfos[account]->ts=newtso;
                QString name;
                    exist=true;
                    name=PeopleInfos[account]->name;
                    sendjo.insert("name",name);
                    sendjo.insert("image",PeopleInfos[account]->image);
                    sendjo.insert("lastmes",PeopleInfos[account]->lastmes);
                    sendjo.insert("personalsign",PeopleInfos[account]->personalsign);
                    //用户存在需要返回对应的朋友列表
                    int friendnum=PeopleInfos[account]->friendaccounts.size();
                    for(int i=0;i<friendnum;i++)
                    {
                        QString fa=PeopleInfos[account]->friendaccounts.at(i);
                        QString friendaccount=PeopleInfos[fa]->account;
                        QString friendimage=PeopleInfos[fa]->image;
                        QString friendname=PeopleInfos[fa]->name;
                        QString friendlastmes=PeopleInfos[fa]->lastmes;
                        QString friendperosnalsign=PeopleInfos[fa]->personalsign;
                        QString fri="friend"+QString::number(i);
                        sendjo.insert(QString(fri+"%1").arg("account"),friendaccount);
                        sendjo.insert(QString(fri+"%1").arg("image"),friendimage);
                        sendjo.insert(QString(fri+"%1").arg("lastmes"),friendlastmes);
                        sendjo.insert(QString(fri+"%1").arg("perosnalsign"),friendperosnalsign);
                        sendjo.insert(QString(fri+"%1").arg("name"),friendname);
                    }
                    //用户存在需要返回历史消息
                    int mesnum=PeopleInfos[account]->historicalmes.size();
                    sendjo.insert("mesnum",mesnum);
                    for(int i=0;i<mesnum;i++)
                    {
                        QString mes=QString("senderaccount:%1;").arg(PeopleInfos[account]->historicalmes.at(i)->mes_senderaccount);
                        mes+=QString("receiveraccount:%1;").arg(PeopleInfos[account]->historicalmes.at(i)->mes_receiveraccount);
                        mes+=QString("time:%1;").arg(PeopleInfos[account]->historicalmes.at(i)->mes_time);
                        mes+=QString("contend:%1;").arg(PeopleInfos[account]->historicalmes.at(i)->mes);
                        QString str=QString("historicalmes%1").arg(QString::number(i));
                        sendjo.insert(str,mes);
                    }
                    
                    
                }
                sendjo.insert("datatype","confirmaccountexist");
                sendjo.insert("exist",exist);
                QJsonDocument sendjd(sendjo);
                newtso->write(sendjd.toJson());
            }
            else if(dt=="usedimage")
            {
                QString account=jo.value("account").toString();
                QString image;
                QJsonObject sendjo;
                if(Accounts.find(account)!=Accounts.end())
                {
                    image=PeopleInfos[account]->image;
                }
                else
                    image=":/res/login_default.png";
                sendjo.insert("datatype","sendusedimage");
                sendjo.insert("usedimage",image);
                QJsonDocument sendjd(sendjo);
                newtso->write(sendjd.toJson());
            }
            else if(dt=="searchpeople")
            {
                QString account=jo.value("account").toString();
                QString mes="datatype:searchpeople,account:"+account;
                ui->meslist->addItem(mes);
                QJsonObject sendjo;
                if(Accounts.find(account)!=Accounts.end()) //用户存在
                {
                    QString image=PeopleInfos[account]->image;
                    QString name=PeopleInfos[account]->name;
                    sendjo.insert("datatype","returnsearchpeople");
                    sendjo.insert("exist",true);
                    sendjo.insert("name",name);
                    sendjo.insert("image",image);
                }
                else  //用户不存在
                {
                    sendjo.insert("datatype","returnsearchpeople");
                    sendjo.insert("exist",false);
                }
                QJsonDocument sendjd(sendjo);
                newtso->write(sendjd.toJson());
            }
            else if(dt=="addpeople")
            {
                QString addingaccount=jo.value("addingaccount").toString();
                QString addedaccount=jo.value("addedaccount").toString();
                QJsonObject sendjo;
                if(Accounts.find(addedaccount)!=Accounts.end()) //用户存在
                {
                    QString image=PeopleInfos[addingaccount]->image;
                    QString name=PeopleInfos[addingaccount]->name;
                    QString extrames=jo.value("extrames").toString();
                    sendjo.insert("datatype","returnaddpeople");
                    sendjo.insert("name",name);
                    sendjo.insert("image",image);
                    sendjo.insert("account",addingaccount);
                    sendjo.insert("extrames",extrames);
                }
                QJsonDocument sendjd(sendjo);
                PeopleInfos[addedaccount]->ts->write(sendjd.toJson());
            }
            else if(dt=="sendmes")
            {
                QString senderaccount=jo.value("senderaccount").toString();
                QString receiveraccount=jo.value("receiveraccount").toString();
                QString sender=jo.value("sender").toString();
                QString condendtype=jo.value("condendtype").toString();
                QString condend=jo.value("condend").toString();
                QString image=jo.value("image").toString();
                QString time=jo.value("time").toString();
                QJsonObject sendjo;
                sendjo.insert("datatype","despatchmes");
                sendjo.insert("senderaccount",senderaccount);
                sendjo.insert("condendtype",condendtype);
                sendjo.insert("condend",condend);
                sendjo.insert("time",time);
                sendjo.insert("image",image);
                QJsonDocument sendjd(sendjo);
                //派送给对端客户端
                PeopleInfos[receiveraccount]->ts->write(sendjd.toJson());
                //持久化存储               PeopleInfos[senderaccount]->historicalmes
                // PeopleInfos[receiveraccount]->historicalmes.push_back();
            }
            else if(dt=="agreeaddpeople")  //同意添加为好友
            {
                QString senderaccount=jo.value("senderaccount").toString();
                QString receiveraccount=jo.value("receiveraccount").toString();
                QString sendername=jo.value("sendername").toString();
                QString senderimage=jo.value("senderimage").toString();
                QJsonObject sendjo;
                sendjo.insert("datatype","successaddpeople");
                sendjo.insert("account",senderaccount);
                sendjo.insert("name",sendername);
                sendjo.insert("image",senderimage);
                QJsonDocument sendjd(sendjo);
                PeopleInfos[receiveraccount]->ts->write(sendjd.toJson());
            }
            else if(dt=="loaddatabase")  //由于本机一些问题导致服务器不能直接从SQLite数据库中读取数据，因此再启动一个项目进行数据库读取
            {
                //加载个人基本信息
                int peoplenum=jo.value("peoplenum").toInt();
                for(int i=0;i<peoplenum;i++)
                {
                    QString account=jo.value(QString("account%1").arg(QString::number(i))).toString();
                    QString image=jo.value(QString("image%1").arg(QString::number(i))).toString();
                    QString secret=jo.value(QString("secret%1").arg(QString::number(i))).toString();
                    QString name=jo.value(QString("name%1").arg(QString::number(i))).toString();
                    QString lastmes=jo.value(QString("lastmes%1").arg(QString::number(i))).toString();
                    QString personalsign=jo.value(QString("personalsign%1").arg(QString::number(i))).toString();
                    Accounts.insert(account);
                    RenewAccounts.push_back(account);
                    PeopleInfos[account]=new peopleinfo;
                    PeopleInfos[account]->init(account,name,secret,image,lastmes,personalsign,nullptr); //用户到来再创建套接字
                }
                ablerenew=true;
            }
            else if(dt=="databasecome") //数据库套接字到来
            {
                ts_sql=newtso;
                QJsonObject sendjo_fr;
                sendjo_fr.insert("datatype","askloaddatabase");
                QJsonDocument jd(sendjo_fr);
                QByteArray bt=jd.toJson();
                bt.append('@');
                qDebug()<<"databasecome:"<<bt;
                qDebug()<<"askloaddatabase-size:"<<ts_sql->write(bt);
                ts_sql->waitForBytesWritten();
            }

        });
    });
    ts->listen(QHostAddress::Any,8081);
}
Widget::~Widget()
{
    delete ui;
}





void Widget::on_pushButton_clicked()
{

    for(QString account:Accounts)
    {
        QJsonObject sendjo_fr;
        sendjo_fr.insert("datatype","askfriendrelation");
        sendjo_fr.insert("account",account);

        QJsonDocument jd(sendjo_fr);
        QByteArray bt=jd.toJson();
        bt.append('@');

        qDebug()<<"askfriendrelation-size:"<<ts_sql->write(bt);
    }

}

